<template>
  <view class="echartsElectricity">
    <view class="title">
      <view class="statistics">
        <view
          v-for="(item, index) in itemList"
          :key="index"
          :class="echartsType == index + 1 ? 'title-active' : ''"
          @click="setEchartsType(index + 1)"
        >
          {{ t(item.name) }}
        </view>
      </view>
      <view class="time">
        <up-subsection
          :list="list"
          :current="timeType"
          @change="timeChange"
          activeColor="#fff"
          inactiveColor="#999999"
          bgColor="#08121E"
        ></up-subsection>
      </view>
    </view>
    <!-- 总电量，总放电量 -->
    <view class="content-electricity" v-if="echartsType == 1">
      <view class="content-box-item content-box-item-1">
        <view class="title">
          {{ t("dashboard.totalCharge") }}({{
            chargeUnit(electricity.charge, 1)
          }})
        </view>

        <view class="bottom-content">
          <view class="num"> {{ chargeUnit(electricity.charge, 0) }} </view>
          <image src="/static/dashboard/discharge.png" mode="" />
        </view>
      </view>
      <view class="content-box-item content-box-item-2">
        <view class="title">
          {{ t("dashboard.totalDischarge") }}
          ({{ chargeUnit(electricity.disCharge, 1) }})
        </view>
        <view class="bottom-content">
          <view class="num"> {{ chargeUnit(electricity.disCharge, 0) }} </view>
          <image src="/static/dashboard/charge.png" mode="" />
        </view>
      </view>
    </view>
    <!-- 收益统计 -->
    <view class="content-electricity" v-if="echartsType == 2">
      <view class="content-box-item content-box-item-1">
        <view class="title">
          <!-- 月收益 -->
          {{
            timeType == 0
              ? t("dashboard.dayEarnings")
              : timeType == 1
              ? t("dashboard.monthlyEarnings")
              : t("dashboard.yearEarnings")
          }}
          ({{ t(moneyUnit(earnings.typeProfit).templete) }})
        </view>

        <view class="bottom-content">
          <view class="num">
            {{ t(moneyUnit(earnings.typeProfit).value) }}
          </view>
          <image src="/static/dashboard/monthlyEarnings.png" mode="" />
        </view>
      </view>
      <view class="content-box-item content-box-item-2">
        <view class="title">
          <!-- 总收益 -->
          {{ t("dashboard.totalRevenue") }}
          ({{ t(moneyUnit(earnings.totalProfit).templete) }})
        </view>
        <view class="bottom-content">
          <view class="num">
            {{ t(moneyUnit(earnings.totalProfit).value) }}
          </view>
          <image src="/static/dashboard/totalRevenue.png" mode="" />
        </view>
      </view>
    </view>
    <!-- 图表 -->
    <view class="echarts-content">
      <view v-if="echartsType == 1">
        <template v-if="chartOption && Object.keys(chartOption).length !== 0">
          <EChartsWrapper :option="chartOption" />
        </template>
        <template v-else>
          <up-empty icon="/static/no-empty.png" :text="t('common.empty')">
          </up-empty>
        </template>
      </view>
      <view v-if="echartsType == 2">
        <template
          v-if="chartEarnings && Object.keys(chartEarnings).length !== 0"
        >
          <EChartsWrapper :option="chartEarnings" />
        </template>
        <template v-else>
          <up-empty icon="/static/no-empty.png" :text="t('common.empty')">
          </up-empty>
        </template>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, defineExpose, computed, onMounted } from "vue";
import apis from "@/apis/index.js";
import {
  chargeUnit,
  powerUnit,
  moneyUnit,
  formatElectricityOfUnit,
  formatElectricity,
  calculateAverage,
  formatMoney,
  formatMoneyOfUnit,
} from "@/utils/utils";
import { useI18n } from "vue-i18n";
const { locale, t } = useI18n();

const selectedLocale = ref(locale.value);

onMounted(() => {
  initData();
});

const props = defineProps({
  isSetEcharts: {
    type: Boolean,
    default: true,
  },

  siteType: {
    type: Number,
    default: 0,
  },
});

watch(
  () => props.isSetEcharts,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      initData();
    }
    // 在这里可以进行一些处理逻辑
  }
);

const echartsType = ref(1);
const timeType = ref(0);

const isChartOptionComputed = computed((data) => {
  return echartsType.value == 1 && data && Object.keys(data).length !== 0;
});

const list = computed(() => {
  return [t("dashboard.day"), t("dashboard.month"), t("dashboard.year")];
});

watch(locale, () => {
  list.value = [t("dashboard.day"), t("dashboard.month"), t("dashboard.year")];
});

const itemList = ref([]);
const hiddenGains = ref(true);
// 收益
const earnings = ref({
  totalProfit: 0,
  typeProfit: 0,
});

// 电量
const electricity = ref({
  charge: "",
  disCharge: "",
});

// 定义图表配置项
const chartOption = ref({});

const chartEarnings = ref({});

const initData = () => {
  // 电
  let params = {
    dateType: timeType.value + 1,
    siteType: props.siteType,
  };
  if (echartsType.value == 1) {
    apis.statistics(params).then((res) => {
      electricity.value = res.data;
    });

    apis.electricityCurve(params).then((res) => {
      if (res.code == 200) {
        let date = [];
        let chargeObjArr = [];
        let disChargeObjArr = [];
        res.data.forEach((item) => {
          date.push(item.date);
          chargeObjArr.push(Number(item.charge));
          disChargeObjArr.push(Number(item.disCharge));
        });
        let arr = [...chargeObjArr, ...disChargeObjArr];
        const averageValue = calculateAverage(arr);
        const unit = chargeUnit(averageValue, 1);
        let newChargeObjArr = [];
        let newDisChargeObjArr = [];
        res.data.forEach((item) => {
          newChargeObjArr.push(
            formatElectricityOfUnit(Number(item.charge), unit)
          );
          newDisChargeObjArr.push(
            formatElectricityOfUnit(Number(item.disCharge), unit)
          );
        });
        if (newChargeObjArr.length > 0 && newDisChargeObjArr.length > 0) {
          const allValues = [...newChargeObjArr, ...newDisChargeObjArr];
          let maxValue = Math.max(...allValues);
          console.log("maxValue", maxValue);
          const maxLength = maxValue.toString().length;
          console.log("maxLength", maxLength);
          const baseLeft = 2; // 基础 left 百分比
          let additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
          if (maxValue > 700) {
            additionalLeft = 12;
          }
          const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%
          console.log("newLeft", newLeft);
          let chart = {
            title: {
              text: unit,
              top: 0,
              left: 2,
              textStyle: {
                fontSize: 10, // 标题字体大小
                color: "#6E7180", // 标题字体颜色，这里设置为红色
              },
            },
            tooltip: {
              show: true,
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                let x = point[0];
                let y = point[1];
                let viewWidth = size.viewSize[0];
                let viewHeight = size.viewSize[1];
                let boxWidth = size.contentSize[0];
                let boxHeight = size.contentSize[1];
                if (x + boxWidth > viewWidth) {
                  x = viewWidth - boxWidth;
                }
                if (y - boxHeight < 0) {
                  y = boxHeight;
                }

                return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
              },
              backgroundColor: "#fff", // 设置背景颜色为白色
              borderColor: "#ccc", // 设置边框颜色
              borderWidth: 1, // 设置边框宽度
              extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
              formatter: function (params) {
                let xAxisValue = params[0].axisValue; // 获取 x 轴时间
                let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
                params.forEach(function (param) {
                  console.log("param", param);
                  tooltipStr += `${param.seriesName}: ${param.value + unit} \n`;
                });
                return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
              },
            },
            legend: {
              // 显示在右上角
              top: "0%",
              right: "5%",
              itemWidth: 12,
              itemHeight: 8,
              textStyle: {
                // 设置图例文字的大小
                fontSize: 10,
                // 设置图例文字的颜色
                color: "#6e7180",
              },
            },
            grid: {
              bottom: "20%", // 调整图表距离底部的距离
              left: newLeft + "%",
              top: "12%",
              right: "4%",
            },
            xAxis: {
              type: "category",
              data: date,
            },
            yAxis: {
              type: "value",
              axisLabel: {
                show: true,
                color: "#6e7180",
              },
              axisTick: {
                lineStyle: {
                  type: "solid", // 设置 y 轴刻度线为实线
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: "dashed", // 设置 y 轴网格线为虚线
                  color: "#6e7180", // 修改 y 轴网格横线颜色
                },
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#6e7180",
                },
              },
            },
            series: [
              {
                name: t("dashboard.charge"),
                type: "bar",
                data: newChargeObjArr,
                barWidth: "30%",
                itemStyle: {
                  color: "#64B7F6",
                },
              },
              {
                name: t("dashboard.discharge"),
                type: "bar",
                data: newDisChargeObjArr,
                barWidth: "30%",
                itemStyle: {
                  color: "#805EDA",
                },
              },
            ],
            dataZoom: [],
          };
          chartOption.value = chart;
        } else {
          chartOption.value = {};
        }
        console.log("chartOption.valuechartOption.value", chartOption.value);
      }
    });
  } else if (echartsType.value == 2) {
    apis.profitStatistics(params).then((res) => {
      earnings.value = res.data;
    });
    apis.profitCurve(params).then((res) => {
      if (res.code == 200) {
        let date = [];
        let profit = [];
        res.data.forEach((item) => {
          profit.push(Number(item.profit));
        });
        if (profit.length > 0) {
          let averageValue = calculateAverage(profit);
          let unit = formatMoney(averageValue).templete;
          let newProfit = [];
          res.data.forEach((item) => {
            date.push(item.date);
            newProfit.push(formatMoneyOfUnit(Number(item.profit), unit));
          });
          // 计算 Y 轴最大数值的字符长度
          const allValues = newProfit;
          const maxValue = Math.max(...allValues);
          const maxLength = maxValue.toString().length;
          const baseLeft = 2; // 基础 left 百分比
          let additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
          if (maxValue > 700) {
            additionalLeft = 12;
          }
          const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%
          let chart = {
            tooltip: {
              show: true,
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                let x = point[0];
                let y = point[1];
                let viewWidth = size.viewSize[0];
                let viewHeight = size.viewSize[1];
                let boxWidth = size.contentSize[0];
                let boxHeight = size.contentSize[1];

                // 确保 tooltip 在页面内完全显示
                if (x + boxWidth > viewWidth) {
                  x = viewWidth - boxWidth;
                }
                if (y - boxHeight < 0) {
                  y = boxHeight;
                }

                return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
              },
              backgroundColor: "#fff", // 设置背景颜色为白色
              borderColor: "#ccc", // 设置边框颜色
              borderWidth: 1, // 设置边框宽度
              extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
              formatter: function (params) {
                let xAxisValue = params[0].axisValue; // 获取 x 轴时间
                let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
                params.forEach(function (param) {
                  tooltipStr += `${param.value + t(unit)} \n`;
                });
                return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
              },
            },
            title: {
              // 万元
              text: t(unit),
              top: 0,
              left: 2,
              textStyle: {
                fontSize: 10, // 标题字体大小
                color: "#6E7180", // 标题字体颜色，这里设置为红色
              },
            },
            xAxis: {
              type: "category",
              data: date,
              axisTick: {
                lineStyle: {
                  type: "dashed", // 设置 x 轴刻度线为虚线
                },
              },
            },
            yAxis: {
              type: "value",
              axisLabel: {
                show: true,
                color: "#6e7180",
              },
              axisTick: {
                lineStyle: {
                  type: "dashed", // 设置 y 轴刻度线为虚线
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: "dashed", // 设置 y 轴网格线为虚线
                  color: "#6e7180", // 修改 x 轴网格横线颜色为红色
                },
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#6e7180",
                },
              },
            },

            legend: {
              icon: "rect",
              right: "5%",
              itemWidth: 12,
              itemHeight: 8,
              itemStyle: {
                borderRadius: 20, // 调整后的圆角值
                borderWidth: 0, // 设置边框宽度为0
              },
              textStyle: {
                // 设置图例文字的大小
                fontSize: 10,
                // 设置图例文字的颜色
                color: "#6e7180",
              },
            },
            grid: {
              bottom: "20%", // 调整图表距离底部的距离
              left: newLeft + "%",
              top: "12%",
              right: "4%",
            },
            series: [
              {
                symbol: "none", // 取消小圆点
                data: newProfit,
                type: "line",
                lineStyle: {
                  color: "#64B7F6", // 修改线条颜色为红色
                },
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "rgba(39, 46, 78, 0.9)", // 渐变起始颜色，降低透明度
                      },
                      {
                        offset: 1,
                        color: "rgba(31, 40, 68, 0.9)", // 渐变结束颜色，降低透明度
                      },
                    ],
                  },
                },
              },
            ],
          };
          chartEarnings.value = chart;
        } else {
          chartEarnings.value = {};
        }
      }
      console.log("chartEarnings", chartEarnings);
    });
  }
};

const setEchartsType = (index) => {
  if (echartsType.value !== index) {
    echartsType.value = index;
    initData();
  }
};
const timeChange = (e) => {
  timeType.value = e;
  initData();
};

const isShowEarnings = () => {
  itemList.value = [{ name: "dashboard.electricityStatistics" }];
  apis
    .profitStatistics({
      dateType: 3,
      siteType: props.siteType,
    })
    .then((res) => {
      if (res.data.totalProfit == 0 && res.data.typeProfit == 0) {
        hiddenGains.value = false;
        echartsType.value = 1;
      } else {
        itemList.value.push({ name: "dashboard.earningsStatistics" });
      }
    });
};

isShowEarnings();

defineExpose({
  isShowEarnings,
});
</script>

<style lang="scss">
.echartsElectricity {
  width: 100%;
  align-items: center;
  background: #132034;
  border-radius: 10rpx;

  .title {
    width: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx 20rpx;
    box-sizing: border-box;

    .statistics {
      width: 290rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-family: PingFang SC Bold;
      font-size: 32rpx;
      font-weight: normal;
      color: #dddddd;

      .title-active {
        color: #64b7f6;
        position: relative;
      }

      .title-active::after {
        content: "";
        position: absolute;
        background: #64b7f6;
        width: 50rpx;
        height: 8rpx;
        left: 50%;
        bottom: -24rpx;
        transform: translateX(-50%);
        border-radius: 10rpx;
      }
    }

    .time {
      width: 50%;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      :deep(.u-subsection) {
        width: 270rpx;
      }

      :deep(.u-subsection--button__bar) {
        width: 90rpx !important;
        background: #64b7f6;
      }
    }
  }

  .content-electricity {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 0 20rpx;
    box-sizing: border-box;

    .content-box-item-1 {
      background-color: #172d48;

      .num {
        color: #6dd6f2;
      }
    }

    .content-box-item-2 {
      background-color: #1e2645;

      .num {
        color: #805eda;
      }
    }

    .content-box-item {
      margin-top: 20rpx;
      width: 299rpx;
      padding: 0rpx 32rpx;
      box-sizing: border-box;
      margin-bottom: 24rpx;
      border-radius: 10rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .bottom-content {
        margin-top: 24rpx;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        .num {
          font-family: D-DIN;
          font-size: 40rpx;
          font-weight: bold;
          margin-top: 24rpx;
          padding-bottom: 30rpx;
        }

        image {
          width: 67rpx;
          height: 71rpx;
          position: relative;
          bottom: -24rpx;
          right: -20rpx;
        }
      }
      .title {
        font-family: Alibaba PuHuiTi 3;
        font-size: 28rpx;
        font-weight: normal;
        font-variation-settings: "opsz" auto;
        color: #eeeeee;
        padding: 30rpx 0 0 0;
        box-sizing: border-box;
      }
    }
  }

  .echarts-content {
    width: 100%;
    // height: 350rpx;
    padding: 0 15rpx;
    box-sizing: border-box;
  }
}
</style>
